﻿using System;
using System.Collections.Generic;

using System.Text;
using NHibernate;
using NHibernate.Criterion;
using OpenGado.DATA.Entities;

namespace OpenGado.DATA
{
 /// <summary>
 /// Manages the unit of measure object
 /// </summary>
    public class UnitOfMeasureDataControl
 {

    private static UnitOfMeasureDataControl unitOfMeasureDataControl;
    private static object  lockUnitOfMeasure = new object();

    private ISession session;

    public ISession Session
    {

        get
        {
               session = FactoryHandler.CreateFactory().OpenSession();
            return session;
        }


    }
        public void CloseSession()
        {
            Session.Close();
        }

     public static UnitOfMeasureDataControl Instance
     {
         
         get
         {
             lock(lockUnitOfMeasure)
                 if(unitOfMeasureDataControl ==null)
                 {
                     unitOfMeasureDataControl = new UnitOfMeasureDataControl();
                 }
             
             return unitOfMeasureDataControl;
         }
     }

    public void Save(UnitOfMeasure unitOfMeasure)
    {
        ISession tsession = Session;

        ITransaction transaction = tsession.BeginTransaction();

        tsession.SaveOrUpdate(unitOfMeasure);

        transaction.Commit();
        tsession.Close();
    }
        
    public  void Delete (UnitOfMeasure unitOfMeasure)
    {
        ISession tsession = Session;

        try
        {
            ITransaction transaction = tsession.BeginTransaction();
            tsession.Delete(unitOfMeasure);

            transaction.Commit();
        }
        catch (Exception ex)
        {

            throw new Exception("Unit you are trying to delete is associated with some Products, delete the products first");
        }

        tsession.Close();
    }

    public UnitOfMeasure GetById(int unitId)
    {
        UnitOfMeasure um = new UnitOfMeasure();

        ISession tsession = Session;
        um = tsession.Get<UnitOfMeasure>(unitId);
        tsession.Close();

        return um;
    }

    public IList<UnitOfMeasure> GetMeasures()
    {

        ISession tsession = Session;
       
        ICriteria criteria = tsession.CreateCriteria<UnitOfMeasure>();
        IList<UnitOfMeasure> units = criteria.List<UnitOfMeasure>();
        tsession.Close();

     
        return units;
    }

    public IList<UnitOfMeasure> Query(String fieldName, String fieldValue)
    {

        ICriteria criteria = Session.CreateCriteria<UnitOfMeasure>();
        criteria.Add(Restrictions.Eq(fieldName,fieldValue));

        IList<UnitOfMeasure> units = criteria.List<UnitOfMeasure>();


        return units;
    }

 }
}
